package com.blacktea.magicapi.work;

import cn.hutool.core.date.SystemClock;
import cn.hutool.core.lang.Validator;
import com.blacktea.magicapi.base.utils.IpUtils;
import com.jd.platform.async.callback.ICallback;
import com.jd.platform.async.callback.IWorker;
import com.jd.platform.async.worker.WorkResult;
import com.jd.platform.async.wrapper.WorkerWrapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @description:
 * @author: black tea
 * @date: 2022/1/27 16:33
 */
@Slf4j
public class MagicUiUserIpBlackWork implements IWorker<HttpServletRequest,Set<String>>, ICallback<HttpServletRequest,Set<String>> {

    @Override
    public Set<String> action(HttpServletRequest username, Map<String, WorkerWrapper> map) {
        // 获取xxx的白名单
        return new HashSet<>(Collections.singletonList("192.168.31.*"));
    }

    @Override
    public Set<String> defaultValue() {
        return new HashSet<>();
    }

    @Override
    public void begin() {
        System.out.println(Thread.currentThread().getName() + "- black-start --" + System.currentTimeMillis());
    }

    @Override
    public void result(boolean success, HttpServletRequest request, WorkResult<Set<String>> workResult) {
        if (success) {
            System.out.println("callback black success--" + SystemClock.now() + "----" + workResult.getResult()
                    + "-threadName:" +Thread.currentThread().getName());
            if (Validator.isEmpty(workResult.getResult())){
                // 没有白名单要求
                return;
            }
            StringJoiner joiner = new StringJoiner(", ");
            workResult.getResult().forEach(joiner::add);
            String ip = IpUtils.getIpAddr(request);
            if (IpUtils.checkLoginIP(ip,joiner.toString())){
                log.info("该ip:{},在黑名单内!",ip);
//                throw new MagicAPIException("所在的区域IP在黑名单范围内,拒绝登录");
            }

        } else {
            System.err.println("callback black failure--" + SystemClock.now() + "----"  + workResult.getResult()
                    + "-threadName:" +Thread.currentThread().getName());
        }
    }
}
